﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using ZuesControls.Helpers;
using ZuesControls.Models;
using ZuesControls.Mvvm;

namespace ZuesControls.Controls
{
    public class ZSTreeView : TreeView
    {
        public ICommand NavItemInernalClickCommand { get; }
        private TextBox textbox;
        private ITreeNode? _draggedItem;
        private string _treeModelName;
        private Point _startposition;
        private TreeViewItem _item;
        private ScrollViewer scroller;
        protected override DependencyObject GetContainerForItemOverride()
        {
            return new ZSTreeViewItem();
        }

        public static readonly DependencyProperty NavItemClickCommandProperty =
     DependencyProperty.Register("NavItemClickCommand", typeof(RelayCommand<object>), typeof(ZSTreeView), new PropertyMetadata(null));

        public RelayCommand<object> NavItemClickCommand
        {
            get { return (RelayCommand<object>)GetValue(NavItemClickCommandProperty); }
            set { SetValue(NavItemClickCommandProperty, value); }
        }

       

        internal ScrollViewer ScrollViewer
        {
            get
            {
                if (scroller == null)
                {
                    scroller = (ScrollViewer)Template.FindName("scroller", this);
                }

                return scroller;
            }
        }

    



        // 重写此方法，确认元素是否为正确的容器类型
        protected override bool IsItemItsOwnContainerOverride(object item)
        {
            return item is ZSTreeViewItem;
        }
        public ZSTreeView()
        {

            this.NavItemInernalClickCommand = new RelayCommand<Tuple<object, MouseButtonEventArgs>>(OnNavItemClick);
            this.PreviewMouseLeftButtonDown += ZSTreeView_MouseLeftButtonDown;
            this.PreviewMouseDoubleClick += ZSTreeView_PreviewMouseDoubleClick;
            this.PreviewMouseMove += ZSTreeView_PreviewMouseMove;

            this.Drop += ZSTreeView_Drop;
        }

        private void ZSTreeView_Drop(object sender, DragEventArgs e)
        {

            var data = e.Data.GetData(_treeModelName);

            if (data is not ITreeNode draggedItem)
                return;
            if (ItemsSource is not IEnumerable rootItems)
                return;
            var targetItem = FindPositionItem(e.GetPosition(this));
            TreeViewItem parentItem = VisualHelper.TryFindParent<TreeViewItem>(_item);
            if (targetItem?.DataContext is ITreeNode target)
            {
                target.Children.Add(draggedItem);
                Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                {
                    targetItem.IsExpanded = true;
                }));

                if (parentItem.DataContext is ITreeNode parent)
                {
                    parent.Children.Remove(draggedItem);
                }
            }
            TreeViewItem item = VisualHelper.TryFindParent<TreeViewItem>(targetItem);
            //UpdataDataContext(item);
            UpdataDataContext(targetItem);
            UpdataDataContext(parentItem);
          
        }

        private void ZSTreeView_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && _draggedItem != null)
            {
                var currentPoint = e.GetPosition(null);
                if (Math.Abs(currentPoint.X - _startposition.X) > SystemParameters.MinimumHorizontalDragDistance ||
                    Math.Abs(currentPoint.Y - _startposition.Y) > SystemParameters.MinimumVerticalDragDistance)
                {
                    var treeView = (ZSTreeView)sender;
                    DragDrop.DoDragDrop(treeView, new DataObject("ITreeNode", _draggedItem), DragDropEffects.Move);
                    _draggedItem = null;
                }
            }
        }

        ///
        private void ZSTreeView_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (e.OriginalSource is DependencyObject)
            {
                TreeViewItem item = GetTreeViewItemFromSource(e.OriginalSource as DependencyObject);
                if (item != null)
                {
                    textbox = VisualHelper.FindChild<TextBox>(item);
                    textbox.Focusable = true;
                    textbox.Focus();
                    textbox.KeyDown -= Textbox_KeyDown;
                    textbox.KeyDown += Textbox_KeyDown;

                    textbox.LostFocus -= Textbox_LostFocus;
                    textbox.LostFocus += Textbox_LostFocus;
                    textbox.IsHitTestVisible = false;
                }
            }
        }

        private void Textbox_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            ZSTreeView treeview = VisualHelper.TryFindParent<ZSTreeView>(sender as DependencyObject);
            if (treeview != null)
            {
                var qfewf = 1;
            }
        }

        private void ZSTreeView_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _startposition = e.GetPosition(null);
            _item = GetTreeViewItemFromSource(e.OriginalSource as DependencyObject);
            if (_item != null)
            {
                _draggedItem = _item.DataContext as ITreeNode;
                _treeModelName = "ITreeNode";
            }
           // e.Handled = true;
        }

        private void Textbox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (textbox != null && textbox.Focusable == true)
                {
                    textbox.Focusable = false;
                    textbox.IsHitTestVisible = true;
                }
            }
        }

        private void TreeView_Drop(object sender, DragEventArgs e)
        {

        }

        private void Textbox_LostFocus(object sender, RoutedEventArgs e)
        {
            textbox.Focusable = false;
            textbox.IsHitTestVisible = true;
        }

        private void OnNavItemClick(Tuple<object, MouseButtonEventArgs>? parameter)
        {

            if (this.NavItemClickCommand != null)
            {
                //命令执行
                this.NavItemClickCommand.Execute(parameter.Item1);
            }
        }
        private static TreeViewItem GetTreeViewItemFromSource(DependencyObject source)
        {
            // 判断当前的源是否就是item本身，否则查找父级控件
            return source is TreeViewItem item ? item : VisualHelper.TryFindParent<TreeViewItem>(source);
        }

        private TreeViewItem FindPositionItem(Point position)
        {
            var hitTest = VisualTreeHelper.HitTest(this, position);
            var hitObject = hitTest?.VisualHit;
            while (hitObject != null && !(hitObject is TreeViewItem))
            {
                hitObject = VisualTreeHelper.GetParent(hitObject);
            }
            return hitObject as TreeViewItem;
        }
        private void RefreshTreeViewItems(ItemsControl parent)
        {
            for (int i = 0; i < parent.Items.Count; i++)
            {
                var item = parent.ItemContainerGenerator.ContainerFromIndex(i) as TreeViewItem;
                if (item != null)
                {
                    // 强制重新评估绑定
                    var dc = item.DataContext;
                    item.DataContext = null;
                    item.DataContext = dc;
                    // 递归对子项也刷新
                    RefreshTreeViewItems(item);
                }
            }
        }

        private void UpdataDataContext(TreeViewItem item)
        {
            var dc = item.DataContext;
            item.DataContext = null;
            item.DataContext = dc;
        }
    }
}
